/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package spring4.context;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 *
 * @author kent
 */
public class TwIDValidator implements ConstraintValidator<ValiadTwID, String> {

    private boolean nulllable;

    @Override
    public void initialize(ValiadTwID constraintAnnotation) {
        this.nulllable = constraintAnnotation.nullable();
    }

    @Override
    public boolean isValid(String twid, ConstraintValidatorContext context) {
        if (nulllable && (twid == null || twid.isEmpty())) {
            return true;
        } else if (twid!=null && twid.matches("^[A-Z]\\d{9}")) {
            byte s[] = twid.getBytes();
            int[] c = new int[11];
            int a[] = {10, 11, 12, 13, 14, 15, 16, 17, 34, 18, 19, 20, 21, 22, 35, 23, 24, 25, 26, 27, 28, 29, 32, 30, 31, 33};
            c[0] = a[ (s[0]) - 65] / 10;
            c[1] = a[ (s[0]) - 65] % 10;
            for (int i = 1; i <= 9; i++) {
                c[i + 1] = s[i] - 48;
            }
            int count = c[0];
            for (int i = 1; i <= 9; i++) {
                count += c[i] * (10 - i);
            }
            return ((count % 10) + c[10]) == 10;
        } else {
            return false;
        }
    }
}
